package com.example.demo.util;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.ResponseEntity;
import org.springframework.web.client.RestTemplate;

import java.time.Instant;

/**
 *  根据IP地址获取详细的地域信息
 *  @project:personGocheck
 *  @class:AddressUtils.java
 *  @author:heguanhua E-mail:37809893@qq.com
 *  @date：Nov 14, 2012 6:38:25 PM
 */
@Slf4j
public class IpAddressUtils {

    public static String getAddresses(String ip){

        // 获取日历
        Instant now = Instant.now();
        // 获取时间戳
        Long time = now.toEpochMilli();
        // 拼接URL
        String urlStr = "http://opendata.baidu.com/api.php?query=" + ip + "&co=&resource_id=6006&t=1588141817229&ie=utf8&oe=gbk&cb=mrz&format=json&_=" + time + "";
        String urlStr_1 = "https://api.cswendu.com/cswd/public/index.php/api/enhance/ip_city?user=public&ip=" + ip + "";
        String urlStr_2 = "http://ip-api.com/json/" + ip + "?lang=zh-CN";

        log.info("查询Url：{}", urlStr);

        RestTemplate restTemplate = new RestTemplate();
        // 发起Get请求
        ResponseEntity<String> response = restTemplate.getForEntity(urlStr, String.class);
        int REQUEST_STATUS = 200;
        if(response.getStatusCodeValue() != REQUEST_STATUS){
            return "查询ip所属地失败";
        }
        String body = response.getBody();
        log.info("地域信息：{}", body);
        int length = body.length();
        // 提取有效数据
        String str = body.substring(8, length -2);
        // str转对象
        JSONObject jsonObject = JSON.parseObject(str);
        // 对象根据key提取数组对象
        JSONArray ja = (JSONArray) jsonObject.get("data");

        if(ja == null || ja.size() == 0){
            return "查询ip所属地失败";
        }
        // 根据数组下标取对象
        JSONObject jo = (JSONObject) ja.get(0);
        // 对象根据key提取有效字符串
        String ipAddress = (String) jo.get("location");
        return ipAddress;
    }
}